package dentex.youtube.downloader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;


import dentex.youtube.downloader.utils.Utils;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SplashScreen extends Activity {

	
	private String videoId;
	private File currentDir;
	private FileArrayAdapter adapter;
	private File privateAppDir;
	private File privateFile;
	private int cpuVers;
	private boolean isCpuSupported;
	private boolean ffmpegInstalled;
	private File extDir;
	private File extFile;
    private File buffer;
	private String Path_out;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        
       

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

	  StrictMode.setThreadPolicy(policy);
        
         privateAppDir = this.getDir("bin", 0);
		 privateFile = new File(privateAppDir, YTD.ffmpegBinName);
		 cpuVers = armCpuVersion();
		 isCpuSupported = (cpuVers > 0) ? true : false;
		 ffmpegInstalled = privateFile.exists();

		 installPlugin();
		 if(ffmpegInstalled){
			 if(isOnline()){
				 
//				 SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(SplashScreen.this);
//	              	Path_out=sharedPrefs.getString("Path_Output", "test@gmail.com");
//	              	if(!Path_out.equals("test@gmail.com")){
//	              		 Intent intent = new Intent(this, StarterService.class);
//	    				 this.startService(intent);
//	              	}else{
//	   				 Toast.makeText(this, "Please set your default reciever wave files ", Toast.LENGTH_LONG).show();
//	   				 settings();
//	              	}
				
	              	 Intent intent = new Intent(this, StarterService.class);
    				 this.startService(intent);
	              	
			 }else{
				 Toast.makeText(this, "Can't use The function of the teewoow without internet connection", Toast.LENGTH_LONG).show();
			 }			 
		 }else{
			 Toast.makeText(this, "Plugin of extract audio from video is not supported by your smartphone", Toast.LENGTH_LONG).show();
		 }
		 
		 
		 ((Button)findViewById(R.id.button_settings)).setOnClickListener(new OnClickListener(){
	            public void onClick(View v) 
	            {   

	            	 Intent i=new Intent(getBaseContext(),QuickPrefsActivity.class);
	                 startActivity(i);
	            }

			
	           });
		 
	  //exportDB();
	  
    }
    private void exportDB(){
    	File sd = Environment.getExternalStorageDirectory();
          	File data = Environment.getDataDirectory();
           FileChannel source=null;
           FileChannel destination=null;
           String currentDBPath = "/data/"+ "dentex.youtube.downloader" +"/databases/Audio_Track";
           String backupDBPath = "Audio_Track_Backup";
           File currentDB = new File(data, currentDBPath);
           File backupDB = new File(sd, backupDBPath);
           try {
                source = new FileInputStream(currentDB).getChannel();
                destination = new FileOutputStream(backupDB).getChannel();
                destination.transferFrom(source, 0, source.size());
                source.close();
                destination.close();
                Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
            } catch(IOException e) {
            	e.printStackTrace();
            }
    }   
    
private void installPlugin(){
		
		if (!ffmpegInstalled && isCpuSupported) {	
			AlertDialog.Builder adb = new AlertDialog.Builder(SplashScreen.this);
            adb.setIcon(android.R.drawable.ic_dialog_info);
            adb.setTitle(getString(R.string.ffmpeg_download_dialog_title));
            
            String msg = getString(R.string.ffmpeg_download_dialog_msg);
            
            extDir = SplashScreen.this.getExternalFilesDir(null);
            extFile = new File(extDir, YTD.ffmpegBinName);
           
            String ffmpegSize;
            if (cpuVers == 5) {
            	ffmpegSize = getString(R.string.ffmpeg_size_armv5);
            } else if (cpuVers == 7) {
            	ffmpegSize = getString(R.string.ffmpeg_size_armv7);
            } else {
            	ffmpegSize = "n.a.";
            }
            String size = getString(R.string.size) + " " + ffmpegSize;

    		File sdcardAppDir = SplashScreen.this.getExternalFilesDir(null);
        	if (sdcardAppDir != null) {
        		if (!extFile.exists()) {
        			
        			 try {
                         AssetManager manager = SplashScreen.this.getBaseContext().getAssets();
                         InputStream mInput = manager.open("ffmpeg_arm7");
                          buffer= new File(Environment.getExternalStorageDirectory(),"ffmpeg_arm7");
                        //    Toast.makeText(getActivity().getBaseContext(), buffer.getPath(), Toast.LENGTH_LONG).show();

                         FileOutputStream byteStream =new FileOutputStream(buffer, true);

                         byte[] bytes = new byte[4096];
                         int len = 0;
                         while ((len = mInput.read(bytes)) > 0)
                         	{ 
                         	byteStream.write(bytes, 0, len);
                             }
                     } catch (FileNotFoundException e) {
                         e.printStackTrace();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
         			copyFfmpegToAppDataDir(SplashScreen.this, buffer, privateFile);

        			
        		}}		
		}
	}
public  void copyFfmpegToAppDataDir(Context context, File src, File dst) {
	try {
		Toast.makeText(context, "YTD: " + context.getString(R.string.ffmpeg_install), Toast.LENGTH_SHORT).show();
		Utils.logger("i", "trying to copy FFmpeg binary to private App dir", "");
		Utils.copyFile(src, dst);
		
		Toast.makeText(context, "YTD: " + context.getString(R.string.ffmpeg_ready), Toast.LENGTH_SHORT).show();
		src.delete();
		
		
		 privateAppDir = this.getDir("bin", 0);
		 privateFile = new File(privateAppDir, YTD.ffmpegBinName);
		 cpuVers = armCpuVersion();
		 isCpuSupported = (cpuVers > 0) ? true : false;
		 ffmpegInstalled = privateFile.exists();

		 if(ffmpegInstalled){
			 if(isOnline()){
				
				 Intent intent = new Intent(this, StarterService.class);
				 this.startService(intent);
				 
//				 SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(SplashScreen.this);
//	              	Path_out=sharedPrefs.getString("Path_Output", "test@gmail.com");
//	              	if(!Path_out.equals("test@gmail.com")){
//	              		 Intent intent = new Intent(this, StarterService.class);
//	    				 this.startService(intent);
//	              	}else{
//	   				 Toast.makeText(this, "Please set your default reciever wave files ", Toast.LENGTH_LONG).show();
//	   				// settings();
//	              	}
				
			 }else{
				 Toast.makeText(this, "Can't use The function of the teewoow without internet connection", Toast.LENGTH_LONG).show();
			 }			 
		 }else{
			 Toast.makeText(this, "Plugin of extract audio from video is not supported by your smartphone", Toast.LENGTH_LONG).show();
		 }
		
		
	} catch (IOException e) {
		Toast.makeText(context, "YTD: " + context.getString(R.string.ffmpeg_install_failed), Toast.LENGTH_SHORT).show();
		Log.e("", "ffmpeg copy to app_bin failed. " + e.getMessage());
	}
}
 private int armCpuVersion() {
 	String cpuAbi = Build.CPU_ABI;
		if (cpuAbi.equals("armeabi-v7a")) {
			return 7;
		} else if (cpuAbi.equals("armeabi")) {
			return 5;
		} else {
			return 0;
		}
	}
 public boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
 
// private void settings(){
//	 
//	 final AlertDialog.Builder alert = new AlertDialog.Builder(SplashScreen.this);
//  	  TextView dialogTxt_id = new TextView(SplashScreen.this);
//       LayoutParams dialogTxt_idLayoutParams
//        = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//       dialogTxt_id.setLayoutParams(dialogTxt_idLayoutParams);
//       dialogTxt_id.setText("You must set up your Teewow" );
//       
//      
//        
//       LinearLayout layout = new LinearLayout(SplashScreen.this);
//       layout.setOrientation(LinearLayout.VERTICAL);
//       layout.addView(dialogTxt_id);
//       
//       alert.setView(layout);
//       alert.setTitle("Settings Application :");
//       alert.setIcon(android.R.drawable.ic_dialog_info);
//        alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
//
//			public void onClick(DialogInterface dialog, int whichButton) {
//			    
//				
//			 Intent mainIntent = new Intent(SplashScreen.this, QuickPrefsActivity.class); 	    
//	         SplashScreen.this.startActivity(mainIntent);
//			}
//
//		
//                          });
//
//        alert.setNegativeButton("Quit Tewoow",
//              new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    	finish();
//                    dialog.cancel();
//            }
//            });
//    alert.show();
//	 
//	 
// }
}
